#coding:utf-8


from datareport.models import *
from db_manager import DBManager 
from config import *
from tool import Tool
from django.db.models import Count
import sys
import time
import datetime

class DataReport(object):
    def __init__(self,cfgParam):
     
        self.cfgParam = cfgParam
        self.manager = DBManager(db,ip,ur,pd)
        self.manager.connect()
        self.tool = Tool()
    def user_info(self):
        """内部网站查询所有玩家信息"""
        try:
	    result = dict()
	    
	    userinfo = list(UserInfo.objects.values())
            result["OnlineNum"] = UserInfo.objects.filter(IsOnline=1).count()
            result["ActiveNum"] = UserInfo.objects.filter(IsActive=1).count()
	    result["sex"]  = list(UserInfo.objects.values('Sex').annotate(Count('Sex')))
	    result["total"] = len(userinfo)
            result["userinfo"] = userinfo
	    ret = {'status':1,'result':result}
	except Exception,e:
	    print e
	    ret = {'status':0,'info_code':10003}
        return ret

    def machine_info(self):
        try: 
	    machineNum= MachineInfo.objects.values().count()
	    ret = {'status':1,'result':machineNum}
	except Exception,e:
	    ret = {'status':0,'info_code':10003}
	return ret 


    def income_info(self):
        """内部网站查询收益状况"""
        retdic = {}
	group  = {}
	#查询过去一周
	today    = time.strftime('%Y-%m-%d',time.localtime(time.time()))
        interval = 7
	for index in range(7):
	    lastday = (datetime.datetime.now() - datetime.timedelta(days = index)).strftime("%Y-%m-%d")
	    basedic = {'recharge_day':lastday,"index":index,"mount":0}
            group[lastday] = basedic 
            print type(lastday)
        start_date = (datetime.datetime.now() - datetime.timedelta(days = interval-1)).strftime("%Y-%m-%d")
        end_date   = today
        #查询总收益
        totalsql = "select sum(mount) as mount from %s " %user_recharge
        totalincome = self.manager.query(totalsql)
        retdic["total"] = totalincome

        try: 
	    incomesql  = " select sum(mount) as mount,recharge_day from %s where recharge_day between '%s' and '%s' group  by recharge_day " %(user_recharge,start_date,end_date)
            incomegroup = self.manager.query(incomesql)
            for row in incomegroup:
		recharge_day = str(row["recharge_day"])
	        if recharge_day in group.keys():
		    group[recharge_day]["mount"] = row["mount"]
            group = group.values()

            retdic["group"] = group
            print retdic
	    ret = {'status':1,'result':retdic}
	except Exception,e:
	    print e
	    ret = {'status':0,'info_code':10003}
	return ret 
        
        
    def recharge_consume_info(self):

        mustkeys = ["querydest"]
        ret = self.tool.check_param(mustkeys,self.cfgParam) 
        if not ret["status"]:
            return ret
        querydest = self.cfgParam["querydest"]

        

        try:
	    #统计总消费
	    totalsql = "select sum(mount) as total_mount from %s " %querydest
	    total_result = self.manager.query(totalsql)
            total_mount = total_result[0]["total_mount"]
            ret["total_mount"] = total_mount

            qrysql = "select a.*,b.NickName from %s as a inner join %s as b  on a.uid = b.UID " %(querydest,user_info)
	    
	    if self.cfgParam.has_key("uid"):
	        uid = int(self.cfgParam["uid"])
	        qrysql = qrysql + "where a.uid = %s" %uid

	    print qrysql
	    result = self.manager.query(qrysql)
	    ret['status'] = 1
	    ret['result'] = result
	except Exception,e:
	    print e
	    ret["info_code"]=10003
	    ret['status'] = 0
        return ret





    	
   
